import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout';
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}


export function generaMenu(routes, data) {
  data.forEach(item => {
    let component;
    if (item.name == 'curd') {
      //component = resolve => require(['@/views/curd/index'], resolve);
    } else {
      component = item.component == '#' ? Layout : resolve => require(['@/views/' + item.component], resolve);
    }
    const menu = {
      path: item.path, 
      component,
      //component:  item.component == '#' ? Layout :() => import('@/views/'+item.component), 因import不知道为啥不行，改下面方法
      hidden: item.is_hidden,
      //children:[],
      redirect: item.redirect,
      name: item.name,
      meta: { title: item.title, id: item.id, roles: item.roles,icon:item.el_icon,noCache:item.is_no_cache ? true :false}
    }
    if (item.children && item.children.length > 0) {
      menu.children = [];//有子集再给，则若子导航只有一个，会自动变成父导航
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}
const state = {
  routes: [],
  addRoutes: [],
  userSetting:{},
  datagrid:{},
  curdpage:{}
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  UPDATE_USER_DATAGRID:(state, datagrid) => {
    state.datagrid = datagrid;
  },
  UPDATE_USER_CURDPAGE:(state, curdpage) => {
    state.curdpage = curdpage;
  },
  UPDATE_USER_SETTING:(state, settings) => {
    state.userSetting = settings;
  },
  UPDATE_USER_SETTING_TABLE_SHOW_FIELD: (state,data) => {
    state.userSetting.datagridTable[data.gridName] = data.data;
  },
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
        getRouters().then(data => {
          //处理动态路由
          let nowRoures = JSON.parse(JSON.stringify(asyncRoutes));
          generaMenu(nowRoures, data.routers);
          let accessedRoutes = [];
          if (roles.includes('admin') && false) {//暂不弄超级管理员
            accessedRoutes = nowRoures || []
          } else {
            accessedRoutes = filterAsyncRoutes(nowRoures, roles)
          }
          commit('SET_ROUTES', accessedRoutes)
          //处理用户个性化配置

          commit('UPDATE_USER_SETTING', data.settings)
          //处理常规页面
          commit('UPDATE_USER_CURDPAGE', data.curdpage)
          commit('UPDATE_USER_DATAGRID', data.datagrid)
          resolve(accessedRoutes)
        });
    })
  },
  saveTableShowField({ commit },data){
    return new Promise((resolve,reject) => {
      commit('UPDATE_USER_SETTING_TABLE_SHOW_FIELD',data);
      let settingData = {};
      settingData.gridName = data.gridName;
      settingData.data = JSON.stringify(data.data);
      saveTableShowField(settingData);
      resolve();
    });




    
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
